package com.zjht.gmcc.bean.tag;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

import com.zjht.gmcc.bean.util.MyConstant;
import com.zjht.gmcc.bean.util.MyFormat;
import com.zjht.gmcc.bean.util.MyJDBC;

/**
 * 分页控件 在JSP使用的关键步骤： 1、String s_page = request.getParameter("page");//当前页码 2、Pager pager=new Pager();//初始化
 * 3、pager.setCurrpage(s_page);//设置当前页;此外，如果一页中记录数有调整，可以使用pager.setPagesize(...)修改默认值MyConstant.PAGESIZE。 4、List rs=pager.getResultSet(sql, para);//sql和para分别为SQL语句和SQL参数 5、遍历rs，在jsp页面显示相应的值 6、在<div
 * id='mydiv'></div>外面，增加语句：<%=pager.getPagerHTML()%>，以便在JSP底部显示分页控件 7、由于分页控件里有page隐藏域hidden，所以<form>必须包围分页控件， 如：<form>...<div id='mydiv'>...</div><%=pager.getPagerHTML()%></form>
 * @author dyh 2010-11-13
 */
public class Pager implements java.io.Serializable {
	private static final long serialVersionUID = 2923158838657451800L;

	int pagesize = MyConstant.PAGESIZE;// 设置每页记录数，默认值是MyConstant.PAGESIZE
	int currpage;// 当前页码
	int firstpage;// 首页码
	int lastpage;// 末页码
	int previouspage;// 上一页
	int nextpage;// 下一页
	int startrow;// 当前页面第一条记录的行数
	int endrow;// 当前页面最后一条记录的行数
	int rowcount;// 总记录数
	int pagecount;// 总页数
	String pagerHTML;// 分页控件HTML

	/**
	 * 根据SQL，输出结果数组集
	 * @author dyh 2010-11-13
	 * @param sql SQL语句(可带“?”参数)
	 * @param para SQL参数集(可为null)
	 * @return 结果数组集(如果元素为空，则其length=0，不存在null的元素)
	 */
	public List<String[]> getResultSet(StringBuilder sql, ArrayList<Object> para) {
		List<String[]> result = null;
		if (sql == null || sql.length() == 0) {

		} else {
			// 检测SQL与参数的正确性
			int paracount = 0;// SQL参数量
			for (int i = 0; i < sql.length(); i++) {
				if (sql.charAt(i) == '?')
					paracount++;
			}
			if (paracount == 0)
				para = null;
			if (paracount > 0 && (para == null || para.size() != paracount)) {// 如果参数个数与SQL中的参数不一致，则不执行SQL

			} else {
				MyJDBC myJDBC = null;
				ResultSet rs = null;
				ResultSetMetaData rsmd = null;
				PreparedStatement ps = null;
				try {
					myJDBC = new MyJDBC();
					StringBuilder sqlCount = new StringBuilder();
					sqlCount.append("SELECT COUNT(*) FROM (");
					sqlCount.append(sql);
					sqlCount.append(")");
					ps = myJDBC.prepareStatement(sqlCount);
					sqlCount = null;
					if (paracount > 0 && para != null) {
						int index = 1;
						for (Object p : para) {
							if (MyFormat.isStrNull(p)) {
								ps.setString(index++, "");
							} else if ("java.lang.Integer".equals(p.getClass().getName())) {
								ps.setInt(index++, Integer.parseInt(p.toString()));
							} else {
								ps.setString(index++, p.toString());
							}
						}
					}
					rs = ps.executeQuery();
					if (rs.next()) {
						setRowcount(rs.getInt(1));
					}
					rs.close();
					rs = null;
					if (getRowcount() > 0) {
						StringBuilder sqlOK = new StringBuilder();
						sqlOK.append("SELECT * FROM (SELECT ROWNUM r,mysql.* FROM (");
						sqlOK.append(sql);
						sqlOK.append(") mysql WHERE ROWNUM <= ? ) WHERE r >= ? ");
						ps = myJDBC.prepareStatement(sqlOK);
						sqlOK = null;
						int index = 1;
						if (paracount > 0 && para != null) {
							for (Object p : para) {
								if (MyFormat.isStrNull(p)) {
									ps.setString(index++, "");
								} else if ("java.lang.Integer".equals(p.getClass().getName())) {
									ps.setInt(index++, Integer.parseInt(p.toString()));
								} else {
									ps.setString(index++, p.toString());
								}
							}
						}
						ps.setInt(index++, getEndrow());
						ps.setInt(index++, getStartrow());
						rs = ps.executeQuery();
						rsmd = rs.getMetaData();
						int colcount = rsmd.getColumnCount();// 字段数
						result = new ArrayList<String[]>();
						String[] row = null;
						while (rs.next()) {
							row = new String[colcount];
							for (index = 1; index < colcount; index++) {
								row[index - 1] = MyFormat.formatStr(rs.getString(index + 1));
							}
							result.add(row);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						rsmd = null;
						if (ps != null) {
							ps.close();
							ps = null;
						}
						if (rs != null) {
							rs.close();
							rs = null;
						}
					} catch (Exception ex) {

					}
					MyJDBC.close(myJDBC);
					sql = null;
					para = null;
				}
			}
		}
		setPagerHTML();
		return result;
	}

	public int getPagesize() {
		return pagesize;
	}

	public void setPagesize(int pagesize) {
		this.pagesize = pagesize;
	}

	public int getRowcount() {
		return rowcount;
	}

	// 初始化各参数
	private void setRowcount(int rowcount) {
		this.rowcount = rowcount;
		setPagecount();
		setStartrow();
		setEndrow();
		setCurrpage();
		setFirstpage();
		setLastpage();
		setPreviouspage();
		setNextpage();
	}

	public int getPagecount() {
		return pagecount;
	}

	private void setPagecount() {
		if (rowcount <= 0)
			this.pagecount = 0;
		else {
			this.pagecount = (int) Math.ceil(rowcount * 1.0 / pagesize);
		}
	}

	public int getStartrow() {
		return startrow;
	}

	private void setStartrow() {
		if (this.currpage > this.pagecount)
			this.currpage = this.pagecount;
		if (this.currpage <= 0)
			this.currpage = 1;
		int row = (this.currpage - 1) * this.pagesize + 1;
		this.startrow = row < 0 ? 0 : row;
	}

	public int getEndrow() {
		return endrow;
	}

	private void setEndrow() {
		int row = currpage * pagesize;
		if (row > rowcount)
			row = rowcount;
		this.endrow = row < 0 ? 0 : row;
	}

	public int getCurrpage() {
		return currpage;
	}

	public void setCurrpage(int currpage) {
		this.currpage = currpage;
	}

	public void setCurrpage(String currpage) {
		try {
			this.currpage = MyFormat.isStrNull(currpage) ? 0 : Integer.parseInt(currpage);
		} catch (Exception e) {
			this.currpage = 0;
		}
	}

	private void setCurrpage() {
		this.currpage = this.rowcount <= 0 ? 0 : this.currpage;
	}

	public String getPagerHTML() {
		return pagerHTML;
	}

	// 设置页面的页码控件
	private void setPagerHTML() {
		StringBuilder pager = new StringBuilder();
		pager.append("<input name='page' type='hidden'/><div id='pager' style='text-align:right;width:99%'>当前第<b><font color='red'>");
		pager.append(this.currpage);
		pager.append("</font></b>页,共<b><font color='red'>");
		pager.append(this.pagecount);
		pager.append("</font></b>页,共<b><font color='red'>");
		pager.append(this.rowcount);
		pager.append("</font></b>条记录");
		if (this.currpage > 1) {
			pager.append("&nbsp;<img src='/img/pager/first.gif' alt='首页' class='imgbutton' onclick='gotoPage(");
			pager.append(this.firstpage);
			pager.append(")'/>");
			pager.append("&nbsp;<img src='/img/pager/previous.gif' alt='上一页' class='imgbutton' onclick='gotoPage(");
			pager.append(this.previouspage);
			pager.append(")'/>");
		} else {
			pager.append("&nbsp;<img src='/img/pager/first_disable.gif' alt='首页'/>");
			pager.append("&nbsp;<img src='/img/pager/previous_disable.gif' alt='上一页'/>");
		}
		if (this.currpage < this.pagecount) {
			pager.append("&nbsp;<img src='/img/pager/next.gif' alt='下一页' class='imgbutton' onclick='gotoPage(");
			pager.append(this.nextpage);
			pager.append(")'/>");
			pager.append("&nbsp;<img src='/img/pager/last.gif' alt='末页' class='imgbutton' onclick='gotoPage(");
			pager.append(this.lastpage);
			pager.append(")'/>");
		} else {
			pager.append("&nbsp;<img src='/img/pager/next_disable.gif' alt='下一页'/>");
			pager.append("&nbsp;<img src='/img/pager/last_disable.gif' alt='末页'/>");
		}
		if (this.pagecount > 1) {
			pager
					.append("&nbsp;转到第<input id='gotopage' type='text' size='3' maxlength='5' onKeyPress='intOnly()'/>页<img src='/img/pager/go.gif' alt='跳转' class='imgbutton' onclick='gotoPage(-1)'/>");
		}
		pager
				.append("</div><script>function gotoPage(page){if(page<0){var p=document.getElementById('gotopage');p.value=p.value.trim();if(p.value==''){alert('请输入页码');p.focus();return;}else{page=parseInt(p.value,10);}}document.getElementById('page').value=page;showDiv();document.forms[0].submit();}</script>");
		this.pagerHTML = pager.toString();
	}

	public void setPagerHTML(String pagerHTML) {
		this.pagerHTML = pagerHTML;
	}

	private void setFirstpage() {
		this.firstpage = this.pagecount <= 0 ? 0 : 1;
	}

	private void setLastpage() {
		this.lastpage = this.pagecount <= 0 ? 0 : this.pagecount;
	}

	private void setPreviouspage() {
		this.previouspage = this.pagecount <= 0 ? 0 : (this.currpage > 1 ? (this.currpage - 1) : 1);
	}

	private void setNextpage() {
		this.nextpage = this.pagecount <= 0 ? 0 : (this.currpage < this.pagecount ? (this.currpage + 1) : this.pagecount);
	}
}